package com.schoolMall.service.impl;

import com.schoolMall.dao.ProductCategoryDao;
import com.schoolMall.dao.ProductDao;
import com.schoolMall.domain.ProductCategory;
import com.schoolMall.dto.ProductCategoryDto;
import com.schoolMall.enums.ProductCategoryStateEnum;
import com.schoolMall.exception.ProductCategoryException;
import com.schoolMall.service.ProductCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author:zyh
 * @Time:2021-08-31-19:28
 * @email:1269231889@qq.com
 */
@Service
public class ProductCategoryServiceImpl implements ProductCategoryService {
    @Autowired
    private ProductCategoryDao productCategoryDao;
    @Autowired
    private ProductDao productDao;

    @Override
    public List<ProductCategory> queryProductCategory(Long shopId) {
        return productCategoryDao.queryProductCategory(shopId);
    }

    @Override
    @Transactional
    public ProductCategoryDto batchInsertProductCategory(List<ProductCategory> productCategoryList) throws ProductCategoryException {
        if (CollectionUtils.isEmpty(productCategoryList)) {
            throw new ProductCategoryException(ProductCategoryStateEnum.EMPTY_LIST.getMsg());
        }
        int batchInsertNum = 0;
        try {
            batchInsertNum = productCategoryDao.batchInsertProductCategory(productCategoryList);
        } catch (ProductCategoryException e) {
            throw new ProductCategoryException(ProductCategoryStateEnum.FAIL.getMsg());
        }
        if (batchInsertNum < 1) {
            throw new ProductCategoryException("插入失败");
        }
        return new ProductCategoryDto(productCategoryList, ProductCategoryStateEnum.SUCCESS);
    }

    @Override
    @Transactional
    public ProductCategoryDto deleteProductCategory(long productCategoryId, long shopId) throws ProductCategoryException {
        try {
            int updateNum = productDao.updateProductCategoryIdToNull(productCategoryId);
        } catch (Exception e) {
            throw new ProductCategoryException("解除关联失败" + e.getMessage());
        }

        try {
            int effectNum = productCategoryDao.deleteProductCategory(productCategoryId, shopId);

            if (effectNum < 1) {
                throw new ProductCategoryException("商品类别删除失败");
            }
        } catch (ProductCategoryException e) {
            throw new ProductCategoryException("delete error" + e.getMessage());
        }

        return new ProductCategoryDto(ProductCategoryStateEnum.SUCCESS);
    }
}
